package com.base.data.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.mysteel.util.ObjectUtils;

import com.base.data.dao.DepartmentDao;
import com.base.data.entity.Department;
import com.mysteel.page.Page;

@Service("departmentSerive")
public class DepartmentServiceImpl implements DepartmentService
{
	@Autowired
	private DepartmentDao departmentDao;

	@Override
	public void saveDepartment(Department d)
	{
		if(ObjectUtils.notNull(d)){
			
			Map<String,Object> params = new HashMap<String,Object>();
			params.put ("name" ,d.getName());
			if(ObjectUtils.isEmpty (departmentDao.query (params))){
				
				if(d.getParentId ()==0L)
				{
					d.setParentId (0);
				}
				if(d.getManagerId ()==0L)
				{
					
					d.setManagerId (0L);
				}
				d.setCompanyName ("空间秀");
				d.setCreateTime (System.currentTimeMillis ());
				
				departmentDao.save(d);	
			}
			
		}
		
		
	}

	@Override
	public void deleteDepartment(long id)
	{
		
		departmentDao.delete(id);
	}

	@Override
	public void updateDepartment(Department d)
	{
		
		Department dp = departmentDao.get (d.getId());
		if(ObjectUtils.notNull (dp)){
			dp.setParentId(d.getParentId ());
			dp.setName(d.getName());
			dp.setMobile (d.getMobile ());
			dp.setDescription (d.getDescription ()); 
			dp.setManagerId (d.getManagerId ());
			
			departmentDao.update(dp);
		}
		
		
	}

	@Override
	public Department getDepartment(long id)
	{
		
		return departmentDao.get(id);
	}

	@Override
	public Page<Department> queryDepartment(Map<String, Object> params,int currentPageNum, int maxPageRowCount)
	{
		
		Page<Department> page = null;

		if (ObjectUtils.isNull(params))
		{
			params = new HashMap<String, Object>(2); 
		}
		
		int count = departmentDao.count(params);    

		if (count > 0) 
		{
			page = new Page<Department>();
			page.setTotalRowCount(count);
			page.setCurrentPageNum(currentPageNum);
			page.setMaxPageRowCount(maxPageRowCount);
			page.setURL(params);
			params.put("startPageRowCount", page.getStartPageRowCount());
			params.put("maxPageRowCount", page.getMaxPageRowCount());

			List<Long> DepartmentIds = departmentDao.query(params);

			if (ObjectUtils.notEmpty(DepartmentIds))
			{
				List<Department> Departments = new ArrayList<Department>(DepartmentIds.size());

				for (long DepartmentId : DepartmentIds)
				{
					Departments.add(getDepartment(DepartmentId));
				}

				page.setDatas(Departments);
			}
		}

		return page; 
	}	
}
